Flow builder
flowOf
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val flow = flowOf("Apple", "Banana", "Cherry")
flow.collect { value ->
println(value)
}
}
asFlow
-
asFlow
是擴展函數, 可將 collections (ex. list, set) 轉換為 flow.
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val list = listOf(1, 2, 3, 4, 5)
val flow = list.asFlow()
flow.collect { value ->
println(value)
}
}
channelFlow
- 使用 Coroutine
channel
建立 flow, 建立一個可以在 corroutine 發出多個值的 flow, 通常用於 concurrency control.
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.launch
fun main() = runBlocking {
val flow = channelFlow {
for (i in 1..5) {
send(i) // emit values to stream
}
}
flow.collect { value ->
println(value)
}
}
- 這個 example 使用
channelFlow
建立一個 flow, 透過 send()
發送 1~5 整數.
- 這個比較少用. 需要在找些資料了解一下.